#!/bin/sh
git --version
git config --global http.schannelCheckRevoke false
git config --global http.sslBackend openssl
git_output=""

export GIT_DEPTH_PARAM="--depth=1"
echo "git_clone_and_fetch: $GIT_REPO_URL branch: $GIT_REPO_BRANCH"

remove_lock_files () {
  echo "It's a git repo"
  if [ -f "$LOCAL_REPO_PATH/.git/shallow.lock" ]; then
    echo "shallow.lock found. delete it."
    rm -f "$LOCAL_REPO_PATH/.git/shallow.lock"
  else
    echo "no shallow.lock"
  fi

  if [ -f "$LOCAL_REPO_PATH/.git/index.lock" ]; then
    echo "index.lock found. delete it."
    rm -f "$LOCAL_REPO_PATH/.git/index.lock"
  else
    echo "no index.lock"
  fi

}

clone_main_repo() {
  echo "call clone_main_repo"
  git config --global --add safe.directory "$LOCAL_REPO_PATH"
  if [ -d "$LOCAL_REPO_PATH/.git" ]; then
    echo "It's a git repo. Only fetch."
  else
    git clone $GIT_REPO_URL "$LOCAL_REPO_PATH" $GIT_DEPTH_PARAM
  fi
  cd "${LOCAL_REPO_PATH}"
  echo "start git fetch new files"
  
  git_output=$(git fetch origin $GIT_REPO_BRANCH $GIT_DEPTH_PARAM && git reset --hard "origin/$GIT_REPO_BRANCH" 2>&1)
}


remove_git_dir() {
  if [ -d "$LOCAL_REPO_PATH/.git" ]; then
    echo "remove .git dir"
    rm -rf "$LOCAL_REPO_PATH/.git"
    git init
  fi
}

check_result_and_retry() {
  echo "call check_result_and_retry"
  if [ $exit_code -ne 0 ] || echo "$git_output" | grep -q "error: non-monotonic" ; then
    cd "${LOCAL_REPO_PATH}"
    remove_git_dir
    if [ -d "$LOCAL_REPO_PATH/.git" ]; then
      echo "It's a git repo"
      remove_lock_files
    else
      echo "no .git dir"
      git init
    fi

    git remote -v
    git remote remove origin
    echo "change git remote url"
    git remote add origin $GIT_REPO_URL
    git remote -v
    echo "retry clone code"
    clone_main_repo
  fi
}

remove_lock_files

clone_main_repo

exit_code=$?
echo "git clone result code: $exit_code"
echo "git_output: $git_output"
check_result_and_retry


exit_code=$?
echo "git clone final result code: $exit_code"
echo "git_output: $git_output"
check_result_and_retry
